package com.Cychat.chat.service;

import com.Cychat.chat.mapper.MessageChatRecordMapper;
import com.Cychat.commons.entity.pojo.MessageChatRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
/**
 * Auther: 刘博文
 * Date: 2025/10/29:20:00
 * Description: 消息服务类
 */
@Service
public class MessageService {

    @Autowired
    private MessageChatRecordMapper messageMapper;

    /**
     * 保存消息到数据库，返回消息ID
     * 如果接收者或发送者不存在（外键约束失败），返回null但不抛出异常
     */
    public Integer saveMessage(Long senderId, Long receiverId, String content, Integer chatType, Integer contentType) {
        try {
            MessageChatRecord message = new MessageChatRecord();
            message.setSenderId(senderId);
            message.setReceiverId(receiverId);
            message.setContent(content);
            message.setChatType(chatType);
            message.setContentType(contentType);
            message.setIsRead(0);
            message.setSendTime(new Date());
            message.setUpdateTime(new Date());
            messageMapper.insert(message);
            return message.getMsgId();
        } catch (DataIntegrityViolationException e) {
            // 外键约束失败：接收者或发送者用户不存在
            System.err.println("保存消息失败：用户不存在（外键约束失败）。senderId: " + senderId + ", receiverId: " + receiverId);
            System.err.println("错误详情: " + e.getMessage());
            // 返回null，但不抛出异常，允许在线消息正常发送
            return null;
        } catch (Exception e) {
            // 其他异常也记录但不抛出，避免影响在线消息发送
            System.err.println("保存消息时发生未知错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取用户未读消息
     */
    public List<MessageChatRecord> getUnreadMessages(Long receiverId) {
        return messageMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MessageChatRecord>()
                        .eq("receiver_id", receiverId)
                        .eq("is_read", 0)
        );
    }

    /**
     * 标记消息为已读
     */
    public void markAsRead(Integer msgId) {
        MessageChatRecord message = new MessageChatRecord();
        message.setMsgId(msgId);
        message.setIsRead(1); // 已读
        message.setUpdateTime(new Date());
        messageMapper.updateById(message);
    }

    /**
     * 批量标记为已读
     */
    public void markAsRead(List<Integer> msgIds) {
        for (Integer msgId : msgIds) {
            markAsRead(msgId);
        }
    }
}
